﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using Logs;

namespace Serializer {
    /// <summary>
    /// 序列化与反序列化
    /// </summary>
    public class SerializerHelper {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="type">待序列化对象类型</param>
        /// <param name="obj">文件流序列化对象</param>
        /// <param name="path">序列化文件位置</param>
        /// <returns>序列化成功与否</returns>
        public bool Serializer(Type type,Object obj,String path) {
            try {
                if(File.Exists(path))
                    File.Delete(path);
                XmlSerializer formatter = new XmlSerializer(type);
                using(FileStream stream = new FileStream(path,FileMode.OpenOrCreate)) {
                    formatter.Serialize(stream,obj);
                    stream.Close();
                }
                return true;
            } catch(Exception ex) {
                Log.Error(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type">待反序列化对象类型</param>
        /// <param name="path">反序列化文件位置</param>
        /// <returns>反序列化的对象</returns>
        public Object Deserialize(Type type,String path) {
            Object obj;
            try {
                if(File.Exists(path)) {
                    XmlSerializer formatter = new XmlSerializer(type);
                    using(FileStream stream = new FileStream(path,FileMode.OpenOrCreate)) {
                        XmlReader xmlReader = new XmlTextReader(stream);
                        obj = formatter.Deserialize(xmlReader);
                        stream.Close();
                    }
                    return obj;
                } else {
                    Log.Error(String.Format("{0}文件缺失！",path));
                    return null;
                }
            } catch(Exception ex) {
                Log.Error(ex.Message);
                return null;
            }
        }
    }
}

